<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * 获取Token接口
 * @author Calvin<hongbinfu@163.com>
 * @readme  :返回结果请使用common_response
 * @help    :具体用法请参考https://github.com/chriskacerguis/codeigniter-restserver
 * @other   :
 *          GET ---  $this->get();
 *          POST --- $this->post();
 *          PUT --- $this->put();
 *         DELETE --- $this->delete();
 */
require(APPPATH.'libraries/Android_Controller.php');
class Auth extends Android_Controller
{
    //private $secret;
   // private $session_key = "__ACCESS_TOKEN__";
   /* public function __construct($config = 'rest')
    {
        parent::__construct($config = 'rest');
    }*/

    public function __construct() {
        parent::__construct();
        //载入逻辑
        $this->load->library("form_validation");
        $this->config->load("form_validation");

        $services = array(
            'register_service',
            'login_service',
            'user_verify_service',
            'user_info_service'
        );
        $this->load->service($services);
    }

    /**
     * App 回调数据
     * @return array
     */
    private function fetch_params(){
        $from = $this->input->post("from",TRUE);
        $expires_date = $this->input->post("expires_date",TRUE);
        $name = $this->input->post("name",TRUE);
        $head_img = $this->input->post("head_img",TRUE);
        $openid = $this->input->post("openid",TRUE);
        $access_token = $this->input->post("access_token",TRUE);
        $client_id = $this->input->post("client_id",TRUE);

        if (empty($from) || empty($expires_date) || empty($name) ||
            empty($openid) || empty($access_token) || empty($client_id)){
            
            return $this->common_response(1003);
        }

        $refresh_token = $this->input->post("refresh_token",TRUE);
        $unionid = $this->input->post("unionid",TRUE);
        //微信 unionid 不能为空
        if($from==2 && empty($unionid)){
            return $this->common_response(1003);
        }

        $data = array(
            'from'      => $from,
            'openid'    => $openid,
            'name'      => $name,
            'head_img'  => $head_img,
            'unionid'   => $unionid,
            "client_id" => $client_id,
            'access_token'  => $access_token,
            'expires_date'  => $expires_date,
            'refresh_token' => $refresh_token,
        );
        return $data;
    }

    /**
     * 第三方登陆
     */
    public function valid_post()
    {

        $data = $this->fetch_params();
        //取用户信息
        $auth_data = $this->login_service->login_by_auth($data);
        if ($auth_data == FALSE) {
            return $this->common_response($this->login_service);
        }

        if ($auth_data['uid'] == 0) {
            return $this->common_response(5052);
        }

        $this->login_service->login_by_uid($auth_data['uid'],$auth_data['from']);
        $client_id = $auth_data['client_id'];

        $platform   = $this->post("platform");
        if (! in_array($platform, array("android", "ios", "pc"))) {
            $platform = "android";
        }

        //$this->login_service->login_uid = $auth_data['uid'];  //防止多端登陆
        $add_fast_login = $this->login_service->fast_login_option($client_id,"",2, $platform);
        isset($add_fast_login['token']) || $add_fast_login['token']="";
        return $this->common_response(0,NULL,array("fast_login_token"=>$add_fast_login['token'],"gid"=>$this->login_service->get_gid()));

           /* 'from' => $this->from,
			'openid' => $me->openid,
			'name' => $user->nickname,
			'head_img' => $user->figureurl,
			'access_token' => $token->access_token,
			'expires_date' => $token->expires,
			'refresh_token' => $token->refresh_token*/
        //$this->login_service->check_openid_bind($openid,$from);
    }

    /**
     * 第三方 绑定 手机号
     * 发送验证码
     * @return array
     */
    public function sms_post(){
        $auth_info = $this->login_service->get_oauth_info();
        if(empty($auth_info)){
            return $this->common_response(1003);
        }

        $this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
        if ($this->form_validation->run() == FALSE)
        {
            return $this->common_response(1003);
        }
        else
        {
            $mobile = $this->post("mobile");
            $check = $this->login_service->check_bind_by_phone($mobile,$auth_info['from']);
            if(!$check) {
                return $this->common_response($this->login_service);
            }

            $send = $this->user_verify_service->send_sms($mobile,User_verify_service::PROCESS_BIND_AUTH_USER);
            if($send === FALSE)
            {
                return $this->common_response($this->user_verify_service);
            }
            return $this->common_response(0);
        }
    }

    /**
     * 第三方帐号绑定(获取)已有帐号
     */
    public function bind_post(){
        $auth_info = $this->login_service->get_oauth_info();

        if(empty($auth_info)){
            return $this->common_response(1003);
        }
        
        if ($auth_info['uid'] == 0) {
            $mobile = $this->post("mobile",TRUE);
            $code = $this->post("code",TRUE);
            if(empty($mobile) || empty($code))
            {
                return $this->common_response(1003);
            }
            $check = $this->user_verify_service->check_sms_code($code,$mobile,User_verify_service::PROCESS_BIND_AUTH_USER);
            if($check===FALSE)
            {
                return $this->common_response($this->user_verify_service);
            } else {
                $check_phone = $this->register_service->check_phone_exists($mobile);
                //不存在手机号则新增帐号
                if (! $check_phone) {
                    $password = Common::random_number(8);
                    $add = $this->register_service->register_by_phone($mobile,$password,'','',array("image"=>$this->user_info_service->fetch_remote_avatar($auth_info['head_img']),"nickname"=>$auth_info['name']),TRUE);
                    if (!$add) {
                        return $this->common_response($this->register_service);
                    }
                    $uid = $this->register_service->get_register_uid();

                } else {
                    $uid = $check_phone['id'];

                    //检测当前手机号是否已绑定了此第三方平台的帐号
                    $unbinded = $this->login_service->check_auth_bind($uid, $auth_info['from']);
                    if (! $unbinded) {
                        return $this->common_response($this->login_service);
                    }

                    //$user_info = $this->user_info_service->get_user_info($uid);
                    $update_data = array();
                    /*if(empty($user_info['image'])){
                        $update_data['image']=$auth_info['head_img'];
                    }
                    if(empty($user_info['nickname'])){
                        $update_data['nickname']=$auth_info['name'];
                    }*/
                    if(!empty($update_data)){
                        $this->user_info_service->update_user_info($uid,$update_data);
                    }
                }
                $bind = $this->login_service->bind_auth_user($auth_info['id'],$uid,$auth_info['from']);
                if (! $bind) {
                    return $this->common_response($this->login_service);
                }
            }
        } else {
            $uid = $auth_info['uid'];
        }
        $this->login_service->login_by_uid($uid, $auth_info['from']);

        //添加快速登陆
        $client_id  = $auth_info['client_id'];
        $platform   = $this->post("platform");
        if (! in_array($platform, array("android", "ios", "pc"))) {
            $platform = "android";
        }

        //$this->login_service->login_uid = $uid;
        $add_fast_login = $this->login_service->fast_login_option($client_id,"",2, $platform);
        !isset($add_fast_login['token']) && $add_fast_login['token']="";
        
        return $this->common_response(0,NULL,array("fast_login_token"=>$add_fast_login['token'],"gid"=>$this->login_service->get_gid()));
    }

}